﻿#include "myChartView.h"
#include <QDebug>
#include <QApplication>
#include <QLineSeries>

#if _MSC_VER >= 1600
#pragma execution_character_set("utf-8")
#endif

myChartView::myChartView(QChart *chart,QWidget *parent)
    : QChartView(chart, parent)
{
}

myChartView::myChartView(QWidget *parent)
    : QChartView(parent)
{
}

myChartView::~myChartView()
{

}


void myChartView::mousePressEvent(QMouseEvent *event)
{
    //左键按下，拖移x轴
    if(event->button() == Qt::LeftButton){
        //改变鼠标形状
        QCursor cursor;
        cursor.setShape(Qt::ClosedHandCursor);
        QApplication::setOverrideCursor(cursor);
        //记录按下鼠标的位置
        pressPos = event->pos();
        befMovePos = pressPos;
        qDebug() << "Press: " << pressPos.rx() << "," << pressPos.ry();
    }
    //右键按下，复原坐标图
    if(event->button() == Qt::RightButton){
        qDebug() << "right button pressed";
//        auto s = this->chart()->series().first();
//        qDebug() << s->userData(0);
//        this->chart->axisX()->setRange(*(end-100).)
    }
}


void myChartView::mouseReleaseEvent(QMouseEvent *event)
{
    //恢复鼠标形状
    Q_UNUSED(event);
    //左键松开，鼠标形状恢复
    if(event->button() == Qt::LeftButton){
        QApplication::restoreOverrideCursor();
    }
}

void myChartView::mouseMoveEvent(QMouseEvent *event)
{
    if(event->buttons() & Qt::LeftButton){
        //记录鼠标当前位置
        curMovePos = event->pos();
        //记录移动距离
        QPoint move = befMovePos-curMovePos;
        this->chart()->scroll(move.rx(), 0);
        //当前位置变为上次移动位置
        befMovePos = curMovePos;
        qDebug() << "Move: " << move.rx() << "," << move.ry();
    }
}

void myChartView::wheelEvent(QWheelEvent *event)
{
    qreal factor = 1.5;
    QPointF curVal = this->chart()->mapToValue(QPointF(event->pos()));
    QValueAxis *axisX = dynamic_cast<QValueAxis*>(this->chart()->axisX());
    const double xMin = axisX->min();
    const double xMax = axisX->max();
    const double xCentral = curVal.x();

    double leftOffset;
    double rightOffset;
    if (event->delta() > 0)
    {//放大
        leftOffset = 1.0 / factor * (xCentral - xMin);
        rightOffset = 1.0 / factor * (xMax - xCentral);
    }
    else
    {//缩小
        leftOffset = 1.0 * factor * (xCentral - xMin);
        rightOffset = 1.0 * factor * (xMax - xCentral);
    }
    this->chart()->axisX()->setRange(xCentral - leftOffset, xCentral + rightOffset);
}




